package com.emokili.ewa.core.frame.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.emokili.ewa.common.exception.BizCodeEnum;
import com.emokili.ewa.common.exception.BusinessException;
import com.emokili.ewa.core.frame.dao.MemberFrameDao;
import com.emokili.ewa.core.frame.entity.FrameEntity;
import com.emokili.ewa.core.frame.entity.MemberFrameEntity;
import com.emokili.ewa.core.frame.service.FrameService;
import com.emokili.ewa.core.frame.service.MemberFrameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class MemberFrameServiceImpl extends ServiceImpl<MemberFrameDao, MemberFrameEntity> implements MemberFrameService {

    @Autowired
    private FrameService frameService;

    @Override
    public void bind(Long memberId, String serialNumber) {
        FrameEntity frameEntity = frameService.getOne(new QueryWrapper<FrameEntity>()
                .eq("serial_number", serialNumber));
        //查看是否存在该序列号
        if(ObjectUtil.isNull(frameEntity)){
            throw new BusinessException(BizCodeEnum.SERIAL_NUMBER_INVALID);
        }
        //查看该序列号是否有绑定过
        List<MemberFrameEntity> memberFrameEntities = list(new QueryWrapper<MemberFrameEntity>()
                .eq("serial_number", serialNumber));
        if(ObjectUtil.isNotEmpty(memberFrameEntities)){
            throw new BusinessException(BizCodeEnum.SERIAL_NUMBER_BINDED);
        }
        MemberFrameEntity memberFrameEntity = new MemberFrameEntity();
        memberFrameEntity.setMemberId(memberId);
        memberFrameEntity.setSerialNumber(serialNumber);
        memberFrameEntity.setCreateTime(new Date());
        memberFrameEntity.setUpdateTime(new Date());
        save(memberFrameEntity);
    }

    @Override
    public void getBindStatus(String serialNumber) {
        FrameEntity frameEntity = frameService.getOne(new QueryWrapper<FrameEntity>()
                .eq("serial_number", serialNumber));
        if(ObjectUtil.isEmpty(frameEntity)){
            throw new BusinessException(BizCodeEnum.DEVICE_NOT_BIND);
        }
    }
}
